package org.ting.e_commerce.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ting.e_commerce.mapper.UserAddressMapper;
import org.ting.e_commerce.model.UserAddress;

import java.util.List;

@Service
public class UserAddressService {
    @Autowired
    UserAddressMapper addressMapper;
    public boolean addUserAddress(UserAddress address) {
        return addressMapper.addUserAddress(address);
    }
    public UserAddress getAddressById(int addressId){
        return addressMapper.getAddressById(addressId);
    }
    public List<UserAddress> getNoDefaultAddress(int userId) {
        return addressMapper.getNoDefaultAddress(userId);
    }
    public UserAddress getDefaultAddress(int userId) {
        return addressMapper.getDefaultAddress(userId);
    }
    public boolean deleteById(int addressId) {
        return addressMapper.deleteById(addressId);
    }

    public boolean updateById(UserAddress address) {
        return addressMapper.updateById(address);
    }

    public boolean setDefaultAddress(int userId, int addressId) {
        //获取默认地址
        UserAddress defaultAddress = addressMapper.getDefaultAddress(userId);

        if(defaultAddress != null) {
            defaultAddress.setDefault(false);
            addressMapper.updateById(defaultAddress);
        }

        //设置默认地址
        UserAddress newDefault = addressMapper.getAddressById(addressId);
        newDefault.setDefault(true);
        return addressMapper.updateById(newDefault);
    }
}
